package org.finesys.codegen.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.finesys.codegen.entity.GenDatasourceConf;
import org.finesys.codegen.service.GenDatasourceConfService;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.SpringContextHolder;
import org.finesys.common.log.core.annotation.LogAnnotation;
import org.finesys.common.log.core.enums.OperateType;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/datasourceConf")
@Tag(name = "数据源管理模块")
public class GenDatasourceConfController {

    /**
     * 数据源管理接口
     */
    private final GenDatasourceConfService genDatasourceConfService;
    /**
     * 动态生成文档
     */
    private final Screw screw;

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param datasourceConf 数据源表
     * @return 分页数据
     */
    @RequestMapping("/page")
    public R<IPage<GenDatasourceConf>> page(Page<GenDatasourceConf> page, GenDatasourceConf datasourceConf) {
        Page<GenDatasourceConf> result = genDatasourceConfService.page(page, Wrappers.query(datasourceConf));
        return R.success(result);
    }

    @GetMapping("/list")
    public R<List<GenDatasourceConf>> list(GenDatasourceConf datasourceConf) {
        return R.success(genDatasourceConfService.list(Wrappers.query(datasourceConf)));
    }

    /**
     * 动态添加数据源
     *
     * @param datasourceConf 数据源信息
     */
    @LogAnnotation(title = "新增数据源", operateType = OperateType.INSERT)
    @PostMapping
    public R<Boolean> addDataSource(@RequestBody GenDatasourceConf datasourceConf) {
        return R.judge(genDatasourceConfService.saveDsByEnc(datasourceConf));
    }

    /**
     * 修改数据源表
     *
     * @param datasourceConf 数据源表
     * @return R
     */
    @LogAnnotation(title = "修改数据源", operateType = OperateType.UPDATE)
    @PutMapping
    public R<Boolean> updateDataSource(@RequestBody GenDatasourceConf datasourceConf) {
        return R.judge(genDatasourceConfService.updateDsByEnc(datasourceConf));
    }

    /**
     * 通过id删除数据源表
     *
     * @param id id
     * @return R
     */
    @LogAnnotation(title = "删除数据源", operateType = OperateType.DELETE)
    @DeleteMapping("/{id}")
    public R<Boolean> deleteDataSource(@RequestBody Long[] ids) {
        return R.judge(genDatasourceConfService.removeByDsId(ids));
    }

    /**
     * 通过id查询数据源表
     *
     * @param id id
     * @return R
     */
    @GetMapping("/{id}")
    public R<GenDatasourceConf> findById(@PathVariable(value = "id") Long id) {
        return R.success(genDatasourceConfService.getById(id));
    }

    /**
     * 生成文档
     */
    @GetMapping("/doc")
    @SneakyThrows
    public void doc(String dsName, HttpServletResponse response) {
        //设置指定的数据源
        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        DynamicDataSourceContextHolder.push(dsName);
        DataSource dataSource = dynamicRoutingDataSource.determineDataSource();
        //设置指定的目标表
        ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
        //生成文档
        ByteArrayOutputStream byteArrayOutputStream = screw.documentGeneration(dataSource, screwProperties);
        byte[] data = byteArrayOutputStream.toByteArray();
        response.reset();
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType(ContentType.OCTET_STREAM.getValue());
        IoUtil.write(response.getOutputStream(), Boolean.FALSE, data);
    }

}
